package com.bt7274.service.impl;

/**
 * @Data 2025/6/10 11:51
 * @Author hp
 * @Version 1.0
 * @Description UserTorrentFavoriteServiceImpl
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bt7274.mapper.UserTorrentFavoriteMapper;
import com.bt7274.pojo.UserTorrentFavorite;
import com.bt7274.service.UserTorrentFavoriteService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserTorrentFavoriteServiceImpl implements UserTorrentFavoriteService {
    @Resource
    private UserTorrentFavoriteMapper userTorrentFavoriteMapper;

    @Override
    public void favoriteTorrent(String userId, Long torrentId) {
        if (!isUserFavorited(userId, torrentId)) {
            UserTorrentFavorite favorite = new UserTorrentFavorite();
            favorite.setUserId(userId);
            favorite.setTorrentId(torrentId);
            userTorrentFavoriteMapper.insert(favorite);
        }
    }

    @Override
    public void unfavoriteTorrent(String userId, Long torrentId) {
        UserTorrentFavorite fav = userTorrentFavoriteMapper.selectOne(
                new QueryWrapper<UserTorrentFavorite>().eq("user_id", userId).eq("torrent_id", torrentId)
        );
        if (fav != null) {
            userTorrentFavoriteMapper.deleteById(fav.getId());
        }
    }

    @Override
    public Long getTorrentFavoriteCount(Long torrentId) {
        return userTorrentFavoriteMapper.selectCount(
                new QueryWrapper<UserTorrentFavorite>().eq("torrent_id", torrentId)
        );
    }

    @Override
    public boolean isUserFavorited(String userId, Long torrentId) {
        return userTorrentFavoriteMapper.selectOne(
                new QueryWrapper<UserTorrentFavorite>().eq("user_id", userId).eq("torrent_id", torrentId)
        ) != null;
    }
}